package com.example.question.list.list2;

import com.example.question.list.list1.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * @Date 2023-07-08
 * @Author Jonathan
 */
public class Code04_160 {
    public static void main(String[] args) {
        Code04_160 code = new Code04_160();
    }


    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        ListNode curA = headA;
        Set<ListNode> visited = new HashSet<>();
        while (curA != null) {
            visited.add(curA);
            curA = curA.next;
        }
        ListNode curB = headB;
        while (curB != null) {
            if (visited.contains(curB)) {
                return curB;
            }
            curB = curB.next;
        }
        return null;
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode a = headA;
        ListNode b = headB;
        while (a != b) {
            a = (a == null) ? headB : a.next;
            b = (b == null) ? headA : b.next;
        }
        return a;
    }


}
